// ---- get network info ---- //
#include <arpa/inet.h>
#include <fstream>
#include <ifaddrs.h>
#include <iostream>
#include <linux/if.h>
#include <string.h>
#include <string>
#include <sys/ioctl.h>
#include <sys/socket.h>

void getNetworkInfo() {
  // get ip, works for linux and mac os, best method
  struct ifaddrs *ifAddrStruct = NULL;

  getifaddrs(&ifAddrStruct);

  // get mac, need to create socket first, may not work for mac os
  struct ifreq ifr;
  int fd = socket(AF_INET, SOCK_DGRAM, 0);

  char local_mac[128] = {0};
  const std::string mac_lock = "20-47-47-73-57-22";

  strcpy(ifr.ifr_name, "eth0"); // only need ethernet card
  if (0 == ioctl(fd, SIOCGIFHWADDR, &ifr)) {
    char temp_str[10] = {0};
    memcpy(temp_str, ifr.ifr_hwaddr.sa_data, 6);
    sprintf(local_mac, "%02x-%02x-%02x-%02x-%02x-%02x", temp_str[0] & 0xff,
            temp_str[1] & 0xff, temp_str[2] & 0xff, temp_str[3] & 0xff,
            temp_str[4] & 0xff, temp_str[5] & 0xff);
  }

  std::ofstream OutFile("../../address.txt");
  OutFile << local_mac;
  OutFile.close();

  printf("Local Mac: %s\n", local_mac);
}

int main(int argc, char **argv) {

  printf("=== network information ===\n");
  getNetworkInfo();

  return 0;
}